package com.cjie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjie.domain.ResponseResult;
import com.cjie.domain.entity.Article;
import com.cjie.domain.entity.Category;
import com.cjie.domain.vo.CategoryVo;
import com.cjie.mapper.CategoryMapper;
import com.cjie.service.ArticleService;
import com.cjie.service.CategoryService;
import com.cjie.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.cjie.constants.SystemConstants.ARTICLE_STATUS_NORMAL;
import static com.cjie.constants.SystemConstants.STATUS_NORMAL;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private ArticleService articleService;

    /**
     * 展示分类接口
     *
     * @return
     */
    @Override
    public ResponseResult getCategoryList() {
        // 仅展示有发布正式文章的分类,并且文章处于正常状态
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.eq(Article::getStatus,ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(articleLambdaQueryWrapper);

        // 获取文章的分类ID ，并且去重
        Set<Long> collect = articleList.stream()
                .map(article -> article.getCategoryId())
                .collect(Collectors.toSet());

        // 查询分类表
        List<Category> categoryList = listByIds(collect);
        categoryList = categoryList.stream()
                .filter(category -> STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        // 封装vo
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);

        return ResponseResult.okResult(categoryVos);
    }
}
